package com.example.choupaiapp.main.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dueeeke.videoplayer.player.VideoViewManager;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.ActivityManager;
import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.common.util.DialogUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.common.view.NoScrollViewPager;
import com.example.choupaiapp.common.view.TabEntity;
import com.example.choupaiapp.main.activity.find.FindBannerWebviewActivity;
import com.example.choupaiapp.main.activity.home.CameraActivity;
import com.example.choupaiapp.main.activity.mine.AboutRichTextActivity;
import com.example.choupaiapp.main.activity.publish.PublishNewActivity;
import com.example.choupaiapp.main.activity.publish.PublishWebViewActivity;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.bean.VersionBean;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.fragment.EmptyFragment;
import com.example.choupaiapp.main.fragment.FindFragment;
import com.example.choupaiapp.main.fragment.HomeFragment;
import com.example.choupaiapp.main.fragment.MessageFragment;
import com.example.choupaiapp.main.fragment.MineFragment;
import com.example.choupaiapp.main.util.LocationUtil;
import com.example.choupaiapp.main.view.DownloadProgressButton;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.hyphenate.chat.EMClient;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.lzy.okserver.task.XExecutor;
import com.orhanobut.logger.Logger;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.utils.UMUtils;
import com.zzhoujay.richtext.RichText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

public class MainActivity extends CommonActivity implements XExecutor.OnAllTaskEndListener {

    @BindView(R.id.viewpager)
    NoScrollViewPager viewpager;
    @BindView(R.id.common_bottom_tab)
    CommonTabLayout commonBottomTab;
    @BindView(R.id.publish)
    ImageView publish;
    private long exitTime;
    private long doubleTime;

    private OkDownload okDownload;
    private List<DownloadTask> values;
    private DownloadTask task;
    private File mFile;

    private ArrayList<Fragment> mFragments = new ArrayList<>();//存放Fragment

    private String[] mTitles = new String[5];
    //未选中图标
    private int[] mIconUnselectIds = new int[5];
    //选中后的图标
    private int[] mIconSelectIds = new int[5];

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private UserInfoBean mUserInfoBean;
    private String token;
    private VersionBean mVersionBean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    //    @Override
    @OnClick({R.id.publish})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.publish:
                mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");
                if (mUserInfoBean == null || TextUtils.isEmpty(token)) {
                    startActivity(ChoseLoginActivity.class);
                } else {
                    HttpParams params = new HttpParams();
                    params.put("token", (String) SharedPreferencesHelp.get("token", ""));
                    finalOkGo.requestHead(RequestType.POSTHEAD, Url.VERIFY_TOKEN, params, Url.VERIFY_TOKEN, new Callback<SendCodeBean>() {
                        @Override
                        public void onSuccess(SendCodeBean sendCodeBean) {
                            if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                if (mUserInfoBean.getIsStandardLook() == 1) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("url", mVersionBean.getReleaseUrl());
                                    startActivity(PublishWebViewActivity.class, bundle);
                                } else {
                                    if (rxPermissions.isGranted(Manifest.permission.CAMERA)) {
                                        if (rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                            showTakePhoto();
                                        } else {
                                            rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(aBoolean -> {
                                                if (aBoolean) {
                                                    showTakePhoto();
                                                } else {
                                                    showToast("拒绝权限可能导致功能不能正常使用");
                                                }
                                            });
                                        }
                                    } else {
                                        rxPermissions.request(Manifest.permission.CAMERA).subscribe(aBoolean -> {
                                            if (aBoolean) {
                                                if (rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                                    showTakePhoto();
                                                } else {
                                                    rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(aBoolean1 -> {
                                                        if (aBoolean1) {
                                                            showTakePhoto();
                                                        } else {
                                                            showToast("拒绝权限可能导致功能不能正常使用");
                                                        }
                                                    });
                                                }
                                            } else {
                                                showToast("拒绝权限可能导致功能不能正常使用");
                                            }
                                        });
                                    }
                                }
                            }
                        }

                        @Override
                        public void onError(Response response) {
                            super.onError(response);
                        }
                    });
                }
                break;
        }
    }

    private void showTakePhoto() {
        Bundle bundle = new Bundle();
        bundle.putString("flag", "out");
        bundle.putInt("count", 9);
        startActivity(CameraActivity.class, bundle);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (null != viewpager) {
            viewpager.setCurrentItem(0);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.equals("perfom_publish")) {
            publish.performClick();
        } else if (event.equals("main_index_1")) {
            commonBottomTab.setCurrentTab(0);
            viewpager.setCurrentItem(0);
        } else if (event.equals("main_index_4")) {
            commonBottomTab.setCurrentTab(3);
            viewpager.setCurrentItem(3);
            EventBus.getDefault().removeStickyEvent(event);
        }
    }

    private class TextClick1 extends ClickableSpan {

        @Override
        public void onClick(View view) {
            Bundle bundle = new Bundle();
            bundle.putString("flag", "1");
            startActivity(AboutRichTextActivity.class, bundle);
        }
    }

    private class TextClick2 extends ClickableSpan {

        @Override
        public void onClick(View view) {
            Bundle bundle2 = new Bundle();
            bundle2.putString("flag", "3");
            startActivity(AboutRichTextActivity.class, bundle2);
        }
    }

    private void tokenVerify() {
        HttpParams params = new HttpParams();
        params.put("token", (String) SharedPreferencesHelp.get("token", ""));
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.VERIFY_TOKEN, params, Url.VERIFY_TOKEN, new Callback<SendCodeBean>() {
            @Override
            public void onSuccess(SendCodeBean sendCodeBean) {
                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                    finalOkGo.requestHead(RequestType.POSTHEAD, Url.WATCH_OTHER_INFO + Config.USER_ID, null, Url.WATCH_OTHER_INFO, new Callback<UserInfoBean>() {
                        @Override
                        public void onSuccess(UserInfoBean userInfoBean) {
                            if (userInfoBean.getCode() == Contacts.SUCCESS) {
                                if (userInfoBean.getUser().getUserId() != Config.USER_ID && userInfoBean.getUser().getSex() != 1) {
                                    EventBus.getDefault().post("main_index_1");
                                    EMClient.getInstance().logout(true);
                                    SharedPreferencesHelp.remove("token");
                                    SharedPreferencesHelp.remove("userInfo");
                                    JPushInterface.deleteAlias(context, 0);
                                    MobclickAgent.onProfileSignOff();
                                    startActivity(ChoseLoginActivity.class);
                                }
                            } else {
                                EventBus.getDefault().post("main_index_1");
                                EMClient.getInstance().logout(true);
                                SharedPreferencesHelp.remove("token");
                                SharedPreferencesHelp.remove("userInfo");
                                JPushInterface.deleteAlias(context, 0);
                                MobclickAgent.onProfileSignOff();
                                startActivity(ChoseLoginActivity.class);
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
            }
        });
    }

    private InputFilter inputFilter = new InputFilter() {

        Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");

        @Override
        public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int
                i3) {
            Matcher matcher = pattern.matcher(charSequence);
            if (!matcher.find()) {
                return null;
            } else {
                showToast("只能输入英文，数字");
                return "";
            }

        }
    };

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        Logger.e(UMUtils.getChannel(context));
        mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");
        token = (String) SharedPreferencesHelp.get("token", "");

        if (mUserInfoBean != null) {
            JPushInterface.setAlias(context, 0, Config.JPUS_PRE + mUserInfoBean.getUser().getUserId());
            CrashReport.setUserId(context, mUserInfoBean.getUser().getMobile());
        }


        mTitles[0] = "首页";
        mIconSelectIds[0] = R.mipmap.home_select;
        mIconUnselectIds[0] = R.mipmap.home_unselect;
        HomeFragment homeFragment = HomeFragment.newInstance();
        mFragments.add(homeFragment);

        mTitles[1] = "发现";
        mIconSelectIds[1] = R.mipmap.find_select;
        mIconUnselectIds[1] = R.mipmap.find_unselect;
        FindFragment findFragment = FindFragment.newInstance();
        mFragments.add(findFragment);

        mTitles[2] = "";
        EmptyFragment emptyFragment = EmptyFragment.newInstance();
        mFragments.add(emptyFragment);

        mTitles[3] = "消息";
        mIconSelectIds[3] = R.mipmap.message_select;
        mIconUnselectIds[3] = R.mipmap.message_unselect;
        MessageFragment messageFragment = MessageFragment.newInstance();
        mFragments.add(messageFragment);

        mTitles[4] = "我的";
        mIconSelectIds[4] = R.mipmap.mine_select;
        mIconUnselectIds[4] = R.mipmap.mine_unselect;
        MineFragment mineFragment = MineFragment.newInstance();
        mFragments.add(mineFragment);

        commonBottomTab.setTextSelectColor(getResources().getColor(R.color.color_333));

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }

        viewpager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        commonBottomTab.setTabData(mTabEntities);

        commonBottomTab.setOnTabSelectListener(new OnTabSelectListener() {

            @Override
            public void onTabSelect(int position) {
//                UnreadMsgUtils.hide(commonBottomTab.getMsgView(position));
                if (position == 0) {
                    viewpager.setCurrentItem(position);
                    EventBus.getDefault().post("mine_position==-1");
                    MobclickAgent.onEvent(ContextUtil.getContext(), "homeID");
                } else if (position == 1) {
                    if (mUserInfoBean == null || TextUtils.isEmpty(token)) {
                        commonBottomTab.setCurrentTab(0);
                        viewpager.setCurrentItem(0);
                        startActivity(ChoseLoginActivity.class);
                    } else {
                        tokenVerify();
                        viewpager.setCurrentItem(position);
                        MobclickAgent.onEvent(ContextUtil.getContext(), "columnID");
                    }
                    EventBus.getDefault().post("mine_position==-1");
                    EventBus.getDefault().post("recommend_position==-1");
                } else if (position == 3) {
                    if (mUserInfoBean == null || TextUtils.isEmpty(token)) {
                        commonBottomTab.setCurrentTab(0);
                        viewpager.setCurrentItem(0);
                        startActivity(ChoseLoginActivity.class);
                    } else {
                        tokenVerify();
                        viewpager.setCurrentItem(position);
                        MobclickAgent.onEvent(ContextUtil.getContext(), "messageID");
                    }
                    EventBus.getDefault().post("mine_position==-1");
                    EventBus.getDefault().post("recommend_position==-1");
                } else if (position == 4) {
                    if (mUserInfoBean == null || TextUtils.isEmpty(token)) {
                        commonBottomTab.setCurrentTab(0);
                        viewpager.setCurrentItem(0);
                        startActivity(ChoseLoginActivity.class);
                    } else {
                        tokenVerify();
                        MobclickAgent.onEvent(ContextUtil.getContext(), "mineID");
                        viewpager.setCurrentItem(position);
                    }
                    EventBus.getDefault().post("recommend_position==-1");
                } else {
                    viewpager.setCurrentItem(position);
                    EventBus.getDefault().post("mine_position==-1");
                    EventBus.getDefault().post("recommend_position==-1");
                }
            }

            @Override
            public void onTabReselect(int position) {
//                UnreadMsgUtils.hide(commonBottomTab.getMsgView(position));
                if (position == 0) {
                    if (System.currentTimeMillis() - doubleTime > 500) {
                        EventBus.getDefault().post("home_scollTo_top");
                        doubleTime = System.currentTimeMillis();
                    } else {
                        EventBus.getDefault().post("home_refresh_data");
                    }
                } else if (position == 1) {
                    if (System.currentTimeMillis() - doubleTime > 500) {
                        EventBus.getDefault().post("find_scollTo_top");
                        doubleTime = System.currentTimeMillis();
                    } else {
                        EventBus.getDefault().post("find_refresh_data");
                    }
                } else if (position == 3) {

                } else if (position == 4) {
                    if (System.currentTimeMillis() - doubleTime > 500) {
                        EventBus.getDefault().post("mine_scollTo_top");
                        doubleTime = System.currentTimeMillis();
                    } else {
                        EventBus.getDefault().post("mine_refresh_data");
                    }
                }
            }

        });

        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position != 2) {
                    if (position == 4 || position == 3) {
                        if (mUserInfoBean == null || TextUtils.isEmpty(token)) {
                            commonBottomTab.setCurrentTab(0);
                            viewpager.setCurrentItem(0);
                            startActivity(ChoseLoginActivity.class);
                        } else {
                            commonBottomTab.setCurrentTab(position);
                        }
                    } else {
                        commonBottomTab.setCurrentTab(position);
                    }

                }

                VideoViewManager.instance().pause();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        viewpager.setCurrentItem(0);
        viewpager.setOffscreenPageLimit(5);

//        UnreadMsgUtils.show(commonBottomTab.getMsgView(3), 0);


        publish.setOnLongClickListener(view -> {
            mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");
            if (mUserInfoBean == null || TextUtils.isEmpty(token)) {
                startActivity(ChoseLoginActivity.class);
            } else {
                HttpParams params = new HttpParams();
                params.put("token", (String) SharedPreferencesHelp.get("token", ""));
                finalOkGo.requestHead(RequestType.POSTHEAD, Url.VERIFY_TOKEN, params, Url.VERIFY_TOKEN, new Callback<SendCodeBean>() {
                    @Override
                    public void onSuccess(SendCodeBean sendCodeBean) {
                        if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                            if (mUserInfoBean.getIsStandardLook() == 1) {
                                Bundle bundle = new Bundle();
                                bundle.putString("url", mVersionBean.getReleaseUrl());
                                startActivity(PublishWebViewActivity.class, bundle);
                            } else {
                                Bundle bundle1 = new Bundle();
                                bundle1.putString("flag", "text");
                                startActivity(PublishNewActivity.class, bundle1);
                                MobclickAgent.onEvent(ContextUtil.getContext(), "publishID");
                            }
                        }
                    }

                    @Override
                    public void onError(Response response) {
                        super.onError(response);
                    }
                });
            }
            return true;
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    @Override
    protected void initData() {
        OkGo.<File>post(Url.WATER_MARKET_IMG)
                .tag(this)
                .execute(new FileCallback(Utils.getPickerFileDirectory(context, "choupai_logo_img").getAbsolutePath(), "choupai_water_img.png") {
                    @Override
                    public void onSuccess(Response<File> response) {
                        Logger.e("保存成功 路径为：" + response.body().getAbsolutePath());
//                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(response.body().getAbsolutePath()))));
                    }

                    @Override
                    public void downloadProgress(Progress progress) {
                        super.downloadProgress(progress);
                    }
                });

        okDownload = OkDownload.getInstance();
        //okDownload.setFolder(Environment.getExternalStorageDirectory() + File.separator + "choupai_apk");
        okDownload.setFolder(Utils.getPickerFileDirectory(context, "choupai_apk").getAbsolutePath());
        okDownload.getThreadPool().setCorePoolSize(3);
        okDownload.addOnAllTaskEndListener(this);
        values = OkDownload.restore(DownloadManager.getInstance().getDownloading());

        finalOkGo.request(RequestType.POST, Url.APP_VERSION_UPDATE, null, Url.APP_VERSION_UPDATE, new Callback<VersionBean>() {
            @Override
            public void onSuccess(VersionBean versionBean) {
                if (versionBean.getCode() == Contacts.SUCCESS) {
                    mVersionBean = versionBean;
                    if (versionBean.getIsInvite() == 1) {
                        DialogUtil dialogUtil = new DialogUtil();
                        dialogUtil.showCenterDialog(context, R.layout.dialog_old_award);
                        dialogUtil.dialog_center.setCancelable(false);
                        dialogUtil.dialog_center.setCanceledOnTouchOutside(false);
                        LinearLayout dialog_new_award = (LinearLayout) dialogUtil.dialog_center_layout;
                        ImageView invite_iv = dialog_new_award.findViewById(R.id.invite_iv);
                        Glide.with(context)
                                .load(versionBean.getImageUrl())
                                .into(invite_iv);

                        invite_iv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Utils.isDoubleClick()) {
                                    return;
                                }
                                HttpParams params = new HttpParams();
                                params.put("token", token);
                                finalOkGo.requestHead(RequestType.POSTHEAD, Url.VERIFY_TOKEN, params, Url.VERIFY_TOKEN, new Callback<SendCodeBean>() {
                                    @Override
                                    public void onSuccess(SendCodeBean sendCodeBean) {
                                        if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                            dialogUtil.dialog_center.dismiss();
                                            EventBus.getDefault().post("dialog_activit " + versionBean.getFloatingImage() + " " + versionBean.getJumpUrl());
                                            //跳转h5
                                            Bundle bundle = new Bundle();
                                            bundle.putString("url", versionBean.getJumpUrl() + "?token=" + token);
                                            startActivity(FindBannerWebviewActivity.class, bundle);
                                        }
                                    }

                                    @Override
                                    public void onError(Response response) {
                                        super.onError(response);
                                    }
                                });
                            }
                        });
                        dialog_new_award.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Utils.isDoubleClick()) {
                                    return;
                                }
                                dialogUtil.dialog_center.dismiss();
                                EventBus.getDefault().post("dialog_activit " + versionBean.getFloatingImage() + " " + versionBean.getJumpUrl());
                            }
                        });

                    }

                    if (mUserInfoBean != null) {
                        if (mUserInfoBean.getIsInvite() == 1) {
                            DialogUtil dialogUtil = new DialogUtil();
                            dialogUtil.showCenterEditDialog(context, R.layout.dialog_invite_input_code);
                            LinearLayout dialog_invite_input_code = (LinearLayout) dialogUtil.dialog_center_edit_layout;

                            ImageView img_bg = dialog_invite_input_code.findViewById(R.id.img_bg);
                            Glide.with(context)
                                    .load(versionBean.getInviteCodeImage())
                                    .into(img_bg);
                            EditText invite_code = dialog_invite_input_code.findViewById(R.id.invite_code);
                            View now_get = dialog_invite_input_code.findViewById(R.id.now_get);
                            View no_tip = dialog_invite_input_code.findViewById(R.id.no_tip);

                            invite_code.setFilters(new InputFilter[]{inputFilter, new InputFilter.LengthFilter(6)});
                            now_get.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (invite_code.getText().toString().length() != 6) {
                                        showImageToas("请输入正确的邀请码");
                                    } else {
                                        dialogUtil.dialog_center_edit.dismiss();
                                        HttpParams params = new HttpParams();
                                        params.put("inviteCode", invite_code.getText().toString());
                                        finalOkGo.requestHead(RequestType.POSTHEAD, Url.USER_ADD_CODE, params, Url.USER_ADD_CODE, new Callback<SendCodeBean>() {
                                            @Override
                                            public void onSuccess(SendCodeBean sendCodeBean) {
                                                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                                    mUserInfoBean.setIsInvite(0);
                                                    SharedPreferencesHelp.putBean("userInfo", mUserInfoBean);
                                                }

                                            }
                                        });
                                    }
                                }
                            });

                            no_tip.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    dialogUtil.dialog_center_edit.dismiss();
                                    HttpParams params = new HttpParams();
                                    params.put("type", 1);
                                    finalOkGo.requestHead(RequestType.POSTHEAD, Url.CANCEL_TIP, params, Url.CANCEL_TIP, new Callback<SendCodeBean>() {
                                        @Override
                                        public void onSuccess(SendCodeBean sendCodeBean) {
                                            if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                                mUserInfoBean.setIsInvite(0);
                                                SharedPreferencesHelp.putBean("userInfo", mUserInfoBean);
                                            }
                                        }
                                    });
                                }
                            });

                            dialog_invite_input_code.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    dialogUtil.dialog_center_edit.dismiss();
                                }
                            });
                        }
                    }

                    boolean isUserSecret = (boolean) SharedPreferencesHelp.get("user_secret", false);

                    if (!isUserSecret) {
                        DialogUtil dialogUtil = new DialogUtil();
                        dialogUtil.showCenterDialog(context, R.layout.dialog_user_secret);
                        dialogUtil.dialog_center.setCanceledOnTouchOutside(false);
                        dialogUtil.dialog_center.setCancelable(false);
                        LinearLayout dialog_user_secret = (LinearLayout) dialogUtil.dialog_center_layout;
                        TextView textView = dialog_user_secret.findViewById(R.id.textview);

                        String s = "欢迎使用丑拍App！在您使用我们产品/服务时，需要连接移动网络或WLAN，产生流量费用请咨询当地运营商。丑拍为了更好的保护您的隐私和信息安全，根据法律相关规定和国家制定了《丑拍法律声明》、《丑拍隐私政策》，请您在使用前务必仔细阅读并透彻理解，您同意并接受全部条款后再开始使用我们的产品/服务。";

                        SpannableStringBuilder spannable = new SpannableStringBuilder(s);
                        spannable.setSpan(new ForegroundColorSpan(Color.parseColor("#D9A937")), s.indexOf("《"), s.indexOf("》") + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //这个一定要记得设置，不然点击不生效textView.setMovementMethod(LinkMovementMethod.getInstance());
                        spannable.setSpan(new ForegroundColorSpan(Color.parseColor("#D9A937")), s.indexOf("《", s.indexOf("、")), s.lastIndexOf("》") + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        spannable.setSpan(new TextClick1(), s.indexOf("《"), s.indexOf("》") + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        spannable.setSpan(new TextClick2(), s.indexOf("《", s.indexOf("、")), s.lastIndexOf("》") + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        //这个一定要记得设置，不然点击不生效
                        textView.setMovementMethod(LinkMovementMethod.getInstance());
                        textView.setText(spannable);

                        TextView agree = dialog_user_secret.findViewById(R.id.agree);
                        agree.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Utils.isDoubleClick()) {
                                    return;
                                }
                                dialogUtil.dialog_center.dismiss();
                                SharedPreferencesHelp.put("user_secret", true);
                            }
                        });
                        TextView no_agree = dialog_user_secret.findViewById(R.id.no_agree);
                        no_agree.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Utils.isDoubleClick()) {
                                    return;
                                }
                                SharedPreferencesHelp.put("user_secret", false);
                                finishActivity();
                            }
                        });
                    }

                    if (!versionBean.getVersions().getAndroidVersions().equals(getAppVersionCode() + "")) {
                        DialogUtil dialogUtil = new DialogUtil();
                        dialogUtil.showCenterDialog(context, R.layout.dialog_update);
//                        if (versionBean.getVersions().getAndroidConstraint() == 1) {
//                            dialogUtil.dialog_center.setCanceledOnTouchOutside(false);
//                            dialogUtil.dialog_center.setCancelable(false);
//                        } else {
//                            dialogUtil.dialog_center.setCanceledOnTouchOutside(true);
//                            dialogUtil.dialog_center.setCancelable(true);
//                        }
                        LinearLayout dialog_update = (LinearLayout) dialogUtil.dialog_center_layout;
                        TextView update_msg = dialog_update.findViewById(R.id.update_msg);
                        update_msg.setText(versionBean.getVersions().getContent());
                        TextView update = dialog_update.findViewById(R.id.update);
                        DownloadProgressButton progressBar = dialog_update.findViewById(R.id.progressBar);
                        update.setOnClickListener(view -> {
                            if (Utils.isDoubleClick()) {
                                return;
                            }
                            // File file = new File(Environment.getExternalStorageDirectory() +
                            //        File.separator + "choupai_apk" + File.separator +
                            //       versionBean.getVersions().getUrl().substring(versionBean.getVersions().getUrl().lastIndexOf("/")));
                            File file = new File(Utils.getPickerFileDirectory(context, "choupai_apk"),
                                    versionBean.getVersions().getUrl().substring(versionBean.getVersions().getUrl().lastIndexOf("/")));
                            if (OkDownload.getInstance().hasTask(versionBean.getVersions().getAndroidVersions())
                                    && file.exists()) {
                                //存在我们就获取任务继续下载
                                task = okDownload.getInstance().getTask(versionBean.getVersions().getAndroidVersions()).
                                        fileName(versionBean.getVersions().getUrl().substring(versionBean.getVersions().getUrl().lastIndexOf("/")));
                            } else {
                                //不存在就移除任务 创建新任务重新下载
                                OkDownload.getInstance().removeTask(versionBean.getVersions().getAndroidVersions());

                                GetRequest<File> request = OkGo.<File>get(versionBean.getVersions().getUrl());
                                task = OkDownload.request(versionBean.getVersions().getAndroidVersions(), request).fileName(versionBean.getVersions().getUrl().substring(versionBean.getVersions().getUrl().lastIndexOf("/"))).save();
                            }
                            task.register(new DownloadListener(versionBean.getVersions().getAndroidVersions()) {
                                @Override
                                public void onStart(Progress progress) {
                                    progressBar.setVisibility(View.VISIBLE);
                                    progressBar.setState(DownloadProgressButton.STATE_DOWNLOADING);
                                }

                                @Override
                                public void onProgress(Progress progress) {
                                    Logger.e(Integer.parseInt(progress.totalSize + "") + "-----" + Float.parseFloat(progress.currentSize + ""));
                                    progressBar.setMaxProgress(Integer.parseInt(progress.totalSize + ""));
                                    progressBar.setProgress(Float.parseFloat(progress.currentSize + ""));
                                    progressBar.postInvalidate();
                                }

                                @Override
                                public void onError(Progress progress) {
                                    Throwable throwable = progress.exception;
                                    if (throwable != null) {
                                        if (throwable instanceof SocketException) {
                                            showToast("网络开小差了...");
                                            cancleDownload(throwable, dialogUtil);
                                        } else if (throwable instanceof UnknownHostException) {
                                            showToast("无网络");
                                            cancleDownload(throwable, dialogUtil);
                                        } else {
                                            OkDownload.getInstance().removeTask(versionBean.getVersions().getAndroidVersions());
                                            cancleDownload(throwable, dialogUtil);
                                        }
                                    }
                                }

                                @Override
                                public void onFinish(File file, Progress progress) {
                                    OkDownload.getInstance().removeTask(versionBean.getVersions().getAndroidVersions());
                                    task.unRegister(this);
                                    dialogUtil.dialog_center.dismiss();
                                    installApk(file);
                                }

                                @Override
                                public void onRemove(Progress progress) {

                                }
                            });
                            task.save();
                            task.start();
                        });
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }
        });
//        Logger.e(NotificationManagerCompat.from(context).areNotificationsEnabled()+"");
    }


    private void cancleDownload(Throwable throwable, DialogUtil dialogUtil) {
        if (dialogUtil != null && dialogUtil.dialog_center != null) {
            dialogUtil.dialog_center.dismiss();
        }
        showImageToas("下载失败，可能导致应用不能使用，请尽快更新");
        throwable.printStackTrace();
    }

    @Override
    public void onAllTaskEnd() {
//        showToast("下载完成");
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (okDownload != null) {
            okDownload.removeOnAllTaskEndListener(this);
        }
        VideoViewManager.instance().release();
        LocationUtil.getInstance().LocationDestroy();
        RichText.recycle();
    }


    /**
     * 再按一次退出 逻辑
     */
    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            showToast("再按一次返回键退出");
            exitTime = System.currentTimeMillis();
        } else {
            ActivityManager.getActivityManager().popAllActivity();
            finishActivity();
        }
//        Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
//        launcherIntent.addCategory(Intent.CATEGORY_HOME);
//        startActivity(launcherIntent);
    }

    protected void installApk(File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //是否有安装位置来源的权限
            boolean haveInstallPermission = getPackageManager().canRequestPackageInstalls();
            if (haveInstallPermission) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    Uri apkUri = FileProvider.getUriForFile(context, getApplicationContext().getPackageName() + ".fileprovider", file);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                } else {
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Uri uri = Uri.fromFile(file);
                    intent.setDataAndType(uri, "application/vnd.android.package-archive");
                }
                startActivity(intent);
            } else {
                mFile = file;
                Uri packageUri = Uri.parse("package:" + getApplicationContext().getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri);
                startActivityForResult(intent, 10086);
            }
        } else {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri apkUri = FileProvider.getUriForFile(context, getApplicationContext().getPackageName() + ".fileprovider", file);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri uri = Uri.fromFile(file);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
            }
            startActivity(intent);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10086) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri apkUri = FileProvider.getUriForFile(context, getApplicationContext().getPackageName() + ".fileprovider", mFile);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri uri = Uri.fromFile(mFile);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
            }
            startActivity(intent);
        }

    }
}
